<template>
	<view class="container">
		<!-- 视频容器 -->
		<view class="video-container">
			<video 
				id="videoPlayer"
				:src="videoUrl" 
				:initial-time="initTime" 
				play-strategy="1"
				autoplay="false"
				@timeupdate="handleTimeUpdate"
				@play="handlePlay"
				@pause="handlePause"
				@seeked="handleSeek"
				controls
				http-cache="true"
				objectFit="contain"
				class="video"
			></video>
		</view>
		<view class="text-view">
			<text>{{text}}</text>
		</view>
		<view class="btn-list">
			<button @click="download()">下载</button>
			<button v-if="this.isStar" @click="unStar()">取消收藏</button>
			<button v-if="!this.isStar" @click="star()">收藏</button>
		</view>
		<!-- 节点列表 -->
		<scroll-view class="scroll-list" scroll-y="true">
			<view 
				v-for="(item, index) in pointList" 
				:key="index" 
				class="list-item"
				@click="gotoTime(item.time)"
			>
				<text class="item-text">{{item.text}}</text>
				<text class="item-time">{{numToTime(item.time)}}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	// 脚本部分保持不变
	export default {
		data() {
			return {
				isDownload:false,
				title:'',
				type:'',
				playID: 0,
				initTime: 0,
				currentTime: 0,
				isStar:false,
				debounceTimer: null,
				videoUrl: '',
				videoContext: null,
				isUserSeeking: false,
				text:'这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频这是一个舞蹈教学视频',
				pointList:[
					// {text:'节点1',time:1},
					// {text:'节点2',time:2},
					// {text:'节点3',time:3},
					// {text:'节点4',time:4},
					// {text:'节点5',time:5},
					// {text:'节点6',time:6},
					// {text:'节点7',time:7},
					// {text:'节点8',time:8},
					// {text:'节点9',time:9},
					// {text:'节点10',time:10},
					// {text:'节点11',time:11},
					// {text:'节点12',time:12},
					// {text:'节点13',time:13},
					// {text:'节点14',time:14},
					// {text:'节点15',time:15},
					// {text:'节点16',time:16},
				]
			}
		},
		methods: {
			// 方法保持不变
			initVideoContext() {
				this.videoContext = uni.createVideoContext('videoPlayer', this)
				
			},
			handleTimeUpdate(e) {
				this.currentTime = e.detail.currentTime
				if (!this.isUserSeeking) {
					this.debounceSave()
				}
			},
			debounceSave() {
				clearTimeout(this.debounceTimer)
				this.debounceTimer = setTimeout(() => {
					this.saveProgress()
				}, 1000)
			},
			saveProgress() {
				if (this.currentTime > 0) {
					uni.setStorageSync(this.playID, this.currentTime)
				}
			},
			handlePlay() {
				if (this.initTime > 0) {
					this.videoContext.seek(this.initTime)
					this.initTime = 0
				}
			},
			handlePause() {
				this.saveProgress()
			},
			handleSeek(e) {
				this.isUserSeeking = true
				this.currentTime = e.detail.currentTime
				this.saveProgress()
				setTimeout(() => {
					this.isUserSeeking = false
				}, 1000)
			},
			numToTime(num) {
			    let minutes = 0;
			    let seconds = 0;
			    if(num<60){
			    	seconds=num;
			    }else{
					minutes=Math.floor(num/60);
					seconds=num-minutes*60;
				}
			    let reMinutes=minutes;
				let reSeconds=seconds;
				if(minutes<10) reMinutes='0'+minutes;
				if(seconds<10) reSeconds='0'+seconds;
			    return `${reMinutes}:${reSeconds}`;
			},
			gotoTime(num){
				this.videoContext.seek(num)
			},
			getVideo(){
				uni.request({
					url:this.baseUrl+'/getVideoPlay',
					method:'POST',
					header: { 'Content-Type': 'application/json' },
					data:{
						videoId:this.playID
					},
					success: (res) => {
						console.log(res)
						this.text=res.data.data.desc;
						this.videoUrl=this.baseUrl+'/stream/'+res.data.data.videoSrc;
						this.title=res.data.data.title;
						this.type=res.data.data.type;
						this.imgSrc=res.data.data.imgSrc;
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			getVideoPoints(){
				uni.request({
					url:this.baseUrl+'/getVideoPoints',
					method:'POST',
					header: { 'Content-Type': 'application/json' },
					data:{
						videoId:this.playID
					},
					success: (res) => {
						console.log(res)
						for(let i=0;i<res.data.data.length;i++){
							this.pointList.push(res.data.data[i])
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			star(){
				if(uni.getStorageSync("starList")==null){
					const starList=[this.playID]
					uni.setStorageSync("starList", JSON.stringify(starList));
					this.isStar=true;
				}else{
					const starList = JSON.parse(uni.getStorageSync("starList") || "[]");
					starList.unshift(this.playID);
					uni.setStorageSync("starList", JSON.stringify(starList));
					this.isStar=true;
				}
				uni.showToast({
					title:'收藏成功',
					duration:2000,
					icon:'success'
				})
			},
			unStar(){
				const starList = JSON.parse(uni.getStorageSync("starList") || "[]");
				const index=starList.indexOf(this.playID);
				starList.splice(index,1);
				uni.setStorageSync("starList", JSON.stringify(starList));
				this.isStar=false;
				uni.showToast({
					title:'取消收藏',
					duration:2000,
					icon:'success'
				})
			},
			async download() {
			  try {
			    // 1. 检查重复下载
			    if (this.isDownload) {
			      uni.showToast({ title: '视频已下载', icon: 'none' });
			      return;
			    }
				const downloadList = JSON.parse(uni.getStorageSync("downloadList") || "[]");
			    // 2. 显示加载状态
			    uni.showLoading({ title: '下载中' });
			
			    // 3. 并行下载（Promise.all 实现并发控制）
			    const [videoPath, imgPath] = await Promise.all([
			      this.downloadAndSave(this.videoUrl),
			      this.downloadAndSave(`${this.baseUrl}/img/${this.imgSrc}`)
			    ]);
			
			    // 4. 更新缓存
			    downloadList.unshift({
			      videoId: this.playID,
			      videoSrc: videoPath,
			      imgSrc: imgPath,
			      title: this.title,
			      desc: this.text,
			      type: this.type,
			      points: this.pointList
			    });
			    console.log(downloadList)
			    uni.setStorageSync("downloadList", JSON.stringify(downloadList));
			    uni.showToast({ title: '下载成功', icon: 'success' });
			    
			  } catch (err) {
			    console.error('下载失败:', err);
			    uni.showToast({ title: '下载失败', icon: 'none' });
			  } finally {
			    uni.hideLoading();
			  }
			},
			// 封装下载+保存为 Promise
			downloadAndSave(url) {
			  return new Promise((resolve, reject) => {
			    uni.downloadFile({
			      url,
			      success: res => {
			        uni.saveFile({
			          tempFilePath: res.tempFilePath,
			          success: saveRes => resolve(saveRes.savedFilePath),
			          fail: reject
			        })
			      },
			      fail: reject
			    })
			  })
			}
		},
		mounted() {
			
		},
		onLoad(options) {
			this.playID = parseInt(options.playID) 
			console.log(this.playID)
			const downloadList = JSON.parse(uni.getStorageSync("downloadList") || "[]");
			for(let i=0;i<downloadList.length;i++){
				if(downloadList[i].videoId==this.playID){
					this.text=downloadList[i].desc,
					this.videoUrl=downloadList[i].videoSrc;
					this.pointList=downloadList[i].points;
					this.isDownload=true;
					break;
				}
			}
			if(!this.isDownload){
				this.getVideo()
				this.getVideoPoints()
			}
			const cachedTime = uni.getStorageSync(this.playID) || 0
			this.initTime = Number(cachedTime)
			const starList = JSON.parse(uni.getStorageSync("starList") || "[]");
			if(starList.indexOf(this.playID)>=0){
				this.isStar=true;
			}
			this.initVideoContext()
		},
		onHide() {
			this.saveProgress()
		},
		onUnload() {
			this.saveProgress()
		}
	}
</script>

<style lang="scss">
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #f5f5f5;
}

.video-container {
	padding: 8rpx;
	background: #000;
	border-radius: 16rpx;
	margin: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
	
	.video {
		width: 100%;
		height: 400rpx;
		border-radius: 8rpx;
		overflow: hidden;
	}
}

.btn-list {
  display: flex;
  justify-content: space-between; /* 左右分布 */
  gap: 20rpx; /* 按钮间距 */
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  
  button {
    flex: 1; /* 等分宽度 */
    height: 80rpx;
    line-height: 80rpx;
    font-size: 30rpx;
    color: #fff;
    background: #007AFF;
    border-radius: 12rpx;
    transition: all 0.3s;
    
    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }
    
    /* 可选：给第二个按钮不同颜色 */
    &:nth-child(2) {
      background: #FF3B30;
    }
  }
}

.text-view {
	/* 新增样式 */
	flex-shrink: 0; /* 防止被压缩 */
	min-height: 80rpx; /* 最小高度 */
	max-height: 300rpx; /* 最大高度 */
	overflow-y: auto; /* 垂直滚动 */
	
	/* 原有样式优化 */
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	padding: 20rpx;
	margin: 0 20rpx 20rpx;
	
	text {
		display: block;
		width: 100%;
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
		white-space: pre-wrap; /* 保留换行 */
		word-break: break-all; /* 强制换行 */
		word-wrap: break-word; /* 长单词换行 */
	}
}

.scroll-list {
	/* 修改高度设置 */
	height: auto !important; /* 移除固定高度 */
	flex: 1;
	min-height: 200rpx; /* 最小高度保证 */
	
	/* 原有样式 */
	background: #fff;
	width: 95%;
	margin:auto;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
	
	.list-item {
		/* 保持原有样式 */
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx;
		border-bottom: 1rpx solid #eee;
		transition: all 0.2s;
		
		/* 点击效果保持 */
		&:active {
			background-color: #f8f8f8;
		}
		
		&:last-child {
			border-bottom: none;
		}
		
		.item-text {
			font-size: 32rpx;
			color: #333;
			font-weight: 400;
		}
		
		.item-time {
			font-size: 24rpx;
			color: #999;
			font-family: monospace;
		}
	}
}

/* 保持原有点击效果 */
.list-item {
	position: relative;
	overflow: hidden;
	
	&::after {
		content: '';
		position: absolute;
		top: 50%;
		left: 50%;
		width: 0;
		height: 0;
		background: rgba(0,0,0,0.1);
		border-radius: 50%;
		transform: translate(-50%, -50%);
		transition: width 0.3s, height 0.3s;
	}
	
	&:active::after {
		width: 200rpx;
		height: 200rpx;
		opacity: 0;
	}
}
</style>